package com.juanjuan.myproject.controller;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;

import javax.jws.WebMethod;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName WsServer
 * @Description TODO
 * @Author ZhaoCun
 * @Date 2023/11/1 21:25
 */
@CrossOrigin
@ServerEndpoint("/ws/{token}")
@Component
public class WsServer {
    static ConcurrentHashMap<String,Session> clients=new ConcurrentHashMap<>();
    @OnOpen
    public void onOpen(Session session,@PathParam("token") String token){
        System.out.println("建立了链接");
        clients.put(token,session);
    }
    @OnMessage
    public void onMessage(String message,@PathParam("token") String token){

        System.out.println("端为"+token+"收到的消息为"+message);
    }
    @OnClose
    public void onClose(@PathParam("token") String token){
        System.out.println(token+"断开链接");
        clients.remove(token);
    }

    @OnError
    public void onError(Throwable throwable){
        throwable.printStackTrace();
    }
}
